package database

import (
	"time"

	log "gitee.com/linxing_3/youye-core/logger"
	"gitee.com/linxing_3/youye-core/sdk/config"
	"gitee.com/linxing_3/youye-core/sdk/pkg"
	toolsDB "gitee.com/linxing_3/youye-core/tools/database"

	toolsLog "gitee.com/linxing_3/youye-core/tools/gorm/logger"

	"gorm.io/gorm"

	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"
)

func NewDatabase(host string, c *config.Database, l log.Logger) (*gorm.DB, error) {

	log.Infof("%s => %s", host, pkg.Green(c.Source))
	registers := make([]toolsDB.ResolverConfigure, len(c.Registers))
	for i := range c.Registers {
		registers[i] = toolsDB.NewResolverConfigure(
			c.Registers[i].Sources,
			c.Registers[i].Replicas,
			c.Registers[i].Policy,
			c.Registers[i].Tables)
	}
	resolverConfig := toolsDB.NewConfigure(c.Source, c.MaxIdleConns, c.MaxOpenConns, c.ConnMaxIdleTime, c.ConnMaxLifeTime, registers)
	db, err := resolverConfig.Init(&gorm.Config{
		NamingStrategy: schema.NamingStrategy{
			SingularTable: true,
		},
		Logger: toolsLog.New(
			logger.Config{
				SlowThreshold: time.Second,
				Colorful:      true,
				LogLevel: logger.LogLevel(
					log.DefaultLogger.Options().Level.LevelForGorm()),
			}, l,
		),
	}, opens(c.Driver))

	if err != nil {
		log.Fatal(pkg.Red(c.Driver+" connect error :"), err)
	} else {
		log.Info(pkg.Green(c.Driver + " connect success !"))
	}
	return db, err
}
